package com.zzzzzz.core.service;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import com.zzzzzz.common.id.UUIDGenerator;
import com.zzzzzz.common.my.MyStringUtils;

@Service
public class UploadService {
	
	@Resource
	private Mongo mongo;
	
	public String saveToMongoImage(CommonsMultipartFile fileData) throws IllegalStateException, IOException{
		FileItem fileItem = fileData.getFileItem();
		DB db = mongo.getDB("image");
		String uuid = UUIDGenerator.get();
		String fileType = MyStringUtils.getFileType(fileItem.getName());
		String fileName = uuid + "." + fileType;
		
		// create a "photo" namespace
		GridFS gfsPhoto = new GridFS(db);
		// get image file from local drive
		GridFSInputFile gfsFile = gfsPhoto.createFile(fileData.getInputStream());
		// set a new filename for identify purpose
		gfsFile.setFilename(fileName);
		gfsFile.setContentType(fileItem.getContentType());
		// save the image file into mongoDB
		gfsFile.save();
		
		return fileName;
		
		//File imageFile = new File("d:\\zhibo8_bg.jpg");
		//fileData.transferTo(imageFile);
	}
	
}
